#!/bin/sh

# uvol prototype
# future development roadmap (aka. to-do):
# * re-implement in C (use libubox, execve lvm/ubi*)
# * hash to validate volume while writing
# * add atomic batch processing for use by container/package manager

if [ -z "$1" ]; then cat <<EOF
uvol storage volume manager

syntax: uvol command ...

commands:
  boot				get active volumes ready (called on boot)
  free				show number of bytes available
  total				show total number of bytes
  align				show sector size in bytes
  list [volname]		list volumes
  create volname type size	create new volume
    type: 'ro' or 'rw'
    size: in bytes
  remove volname		delete volume
  device volname		show block device for mounting
  size volname			show size of volume
  up volname			get volume ready for mounting
  down volname			take volume down after unmounting
  status volname		return status of volume
    return code: 0 - volume is ready for use
                 1 - volume is not ready for use
                 2 - volume doesn'y exist
  write volname size		write to volume from stdin, size in bytes
EOF
	return 22
fi

uvol_backend=
backends_tried=

for backend in /usr/libexec/uvol/*.sh; do
	total=$($backend total)
	backends_tried="$backends_tried $($backend name)"
	[ "$total" ] && uvol_backend=$backend
done

if [ -z "$uvol_backend" ]; then
	echo "No backend available. (tried:$backends_tried)"
	echo "To setup devices with block storage install 'autopart'."
	return 2
fi

flock -x /tmp/run/uvol.lock "$uvol_backend" "$@"
